package com.zhangjg.database;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public abstract class SelectDao<Bean> extends SuperDao<Bean> {
    
    protected abstract Bean loadBean(ResultSet rs);

    public List<Bean> select(Object obj) {
        if (obj == null)
            return null;
        Map<String, Object[]> map = this.getFieldInfo(obj);
        if (map == null)
            return null;
        StringBuilder fieldNames = new StringBuilder();
        List<Object> params = new ArrayList<Object>();
        for (String key : map.keySet()) {
            if (key.equals("table_name"))
                continue;
            Object o[] = (Object[]) map.get(key);
            if (o[0] == null || String.valueOf(o[0]).equals("0")) {
                continue;
            }
            if (fieldNames.length() == 0) {
                fieldNames.append(key).append("=?");
            } else {
                fieldNames.append(" and ").append(key).append("=?");
            }
            params.add(o[0]);
        }
        String tableName = (String) ((Object[]) map.get("table_name"))[0];
        StringBuilder sql = new StringBuilder();
        sql.append("select * from ").append(tableName.toUpperCase()).append(" where ").append(fieldNames.toString());
        return select(sql.toString(), params);
    }

    public List<Bean> select(String sql,List<Object> params ) {
        Connection con = getUsedConnection();
        if (con == null) return null;

        ResultSet rs = null;
        PreparedStatement stm = null;
        try {
            stm = con.prepareStatement(sql);
            if (stm == null) return null;
            if(params!=null){
                for(int i = 0; i < params.size(); i++) {
                    stm.setObject(i+1, params.get(i));
                }
            }
            rs = stm.executeQuery();
            if (rs == null)  return null;
            
            List<Bean> beans = new LinkedList<Bean>();
            while (rs.next()) {
                Bean bean = loadBean(rs);
                beans.add(bean);
            }
            return beans;
        } catch (SQLException e) {
            log.error(e.getMessage());
            return null;
        } finally {
            if (rs != null) try {rs.close();} catch (SQLException e) {log.error(e.getMessage());}
            if (stm != null) try{ stm.close();} catch (SQLException e) {log.error(e.getMessage());}
            if (DBManager.DbRelatedDs.DS == getUsedDsType() && (con != null)) {
                try {if (con != null) con.close();} catch (SQLException e) {log.error(e.getMessage());}
            }
        }
    }
}
